<template>
<div class="container">
  <el-card class="box-card first">
    <div slot="header"><span>设置发券对象</span><span class="tips">当前剩余使用次数{{interest}}次</span></div>
    <div>
      <el-row>
        <el-col :span="23">
          <el-form :inline="true" size="mini" label-width="80px" class="ruleForm">
            <el-form-item label="当前油站">
              <el-select size="mini" v-model="ruleForm.gasId" placeholder="请选择当前油站" @change="handleData($event, 'state')">
                <el-option v-for="item in gasOptions" :key="item.gasId" :value="item.gasId" :label="item.gasName"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="常用油型">
              <el-select v-model="ruleForm.lastOrderOilNo" placeholder="请选择常用油型" @change="handleData">
                <el-option v-for="item in oilOptions" :key="item.id" :value="item.id" :label="item.oilNum"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="周边范围">
              <el-select v-model="ruleForm.distance" placeholder="请选择周边范围" @change="handleData">
                <el-option v-for="item in aroundOptions" :key="item.key" :value="item.key" :label="item.value"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="活跃时间">
              <el-select v-model="ruleForm.laterTime" placeholder="请选择活跃时间" @change="handleData">
                <el-option v-for="item in timeOptions" :key="item.key" :value="item.key" :label="item.value"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="是否有本站优惠券" label-width="130px" prop="hasCoupon">
              <el-radio-group v-model="ruleForm.hasCoupon" @change="handleData">
                <el-radio label="2">全部</el-radio>
                <el-radio label="1">是</el-radio>
                <el-radio label="0">否</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-form>
        </el-col>
        <el-col :span="1">
          <el-button type="primary" @click="searchList" size="mini">查询</el-button>
        </el-col>
      </el-row>
    </div>
  </el-card>
  <div class="accord">
    <span>符合发券人数：</span>
    <span>{{allTotal}}人</span>
  </div>
  <el-card class="box-card">
    <div slot="header"><span>设置发券人数</span></div>
    <div class="people-warp">
      <el-radio-group v-model="sendType" @change="handleClear">
        <el-radio label="0">全部</el-radio>
        <el-radio label="1">手动选择</el-radio>
        <el-radio label="2">自定义数量</el-radio>
      </el-radio-group>
      <div class="people" v-if="sendType === '2'">
        <el-form :model="ruleSelf" status-icon :rules="rules" ref="ruleSelf" label-width="20px">
          <el-form-item prop="userNum">
            <el-input size="mini" v-model="ruleSelf.userNum" placeholder="填写人数"></el-input><span>人</span>
          </el-form-item>
        </el-form>
      </div>
    </div>
  </el-card>
  <div class="accord"><span>勾选发券人数：</span><span>{{multipleSelection.length}}人</span></div>
  <el-card class="box-card">
    <div class="call">
      <el-button type="primary" @click="callBackNow" size="medium">立即召唤</el-button>
      <span style="margin-left:10px; color:#ccc; font-size: 14px;">如果选中数量超过{{valid.max_user_size.max}}，系统默认给前{{valid.max_user_size.max}}用户发放优惠券</span>
    </div>
    <div class="table">
      <el-table v-loading="loading" stripe ref="multipleTable" height="400" :data="tableData" tooltip-effect="dark" style="width: 100%;" size="small" :row-key="getRowKeys" border @selection-change="handleSelectionChange">
        <el-table-column v-if="sendType === '1'" type="selection" :reserve-selection="true" width="55"></el-table-column>
        <el-table-column type="index" label="序号" width="66" align="center">
          <template  slot-scope="scope">
          {{scope.$index+(pageOptions.pageIndex - 1) * pageOptions.pageSize + 1}}
          </template>
        </el-table-column>
        <el-table-column  align="center" prop="lastOrderOilName" label="常用油型"></el-table-column>
        <el-table-column  align="center" prop="distance" label="与油站距离（KM）"></el-table-column>
        <el-table-column  align="center" prop="phone" label="联系方式"></el-table-column>
        <el-table-column  align="center" prop="laterTime" label="用户打开APP时间"></el-table-column>
      </el-table>
      <div class="block">
        <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="pageOptions.pageIndex" :page-sizes="pageSizes" :page-size="pageOptions.pageSizes" layout="total, sizes, prev, pager, next" :total="allTotal">
        </el-pagination>
      </div>
    </div>
  </el-card>
  <el-dialog title="请选择优惠券" @closed="resetInfo=false" :center="true" :close-on-click-modal="false" width="1000px" :visible.sync="dialogTableVisible">
    <aroundDriver v-if="resetInfo" @handelClose="handelClose" :type="type" :passParams="passParams" :multipleSelections="multipleSelection"></aroundDriver>
  </el-dialog>
</div>
</template>

<script>
import { aroundDriverList, activeSelect, isCreateActive, getAllGasInfoList, aroundOilNum, checkDoor, queryInterest } from '@/api/market'
import aroundDriver from './components/callBackAroundDialog'
export default {
  data() {
     const validatePass = (rule, value, callback) => {
       if ( value < 0 || value > this.valid.max_user_size.max || !/(^[1-9]\d*$)/.test(value)) {
          callback(new Error(`输入1-${this.valid.max_user_size.max}正整数`))
          this.ruleSelf.userNum = ''
       } else {
         callback()
       }
    }
    return {
      resetInfo: true,
      loading: false,
      type: 'around',
      dialogTableVisible: false,
      ruleForm: {
        gasId: '', // 油站id
        lastOrderOilNo: '', // 常用油号
        distance: '', // 周边范围
        laterTime: '', // 活跃时间
        hasCoupon: '2' // 是否有油站优惠券
      },
      gasOptions: [], // 当前油站仓库
      oilOptions: [], // 常用油型仓库
      aroundOptions: [], // 周边范围仓库
      timeOptions: [], // 活跃时间仓库
      sendType: '0', // 设置发券人数类型
      tableData: [],
      pageSizes: [10],
      pageOptions: {
        pageIndex: 1, // 当前页
        pageSize: 10 // 每页个数
      },
      allTotal: 0,
      multipleSelection: [],
      passParams: {},
      valid: {
        max_user_size: {}
      },
      ruleSelf: { userNum: '' },// 用户自定义数量
      rules:{ userNum: [{ validator: validatePass, trigger: 'blur' }] },
      interest: 0
    }
  },
  components: {
    aroundDriver
  },
  methods: {
    // 切换条件，自动刷新数据
    async handleData (val, type) {
      if(type === 'state') {
        this.queryInterest(val)
        const res = await aroundOilNum({ gasId: val })
        if(res.code !== 200) return
        this.oilOptions = res.result
        this.ruleForm.lastOrderOilNo = res.result[0].id
      }
      this.searchList()
    },
    // 子组件关闭
    handelClose () {
      this.dialogTableVisible = false
    },
    // 绑定唯一选中值
    getRowKeys(row) {
      return row.userId
    },
    // 记录选中值
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    // 查询方法
    searchList () {
      this.pageOptions.pageIndex = 1
      this.pageOptions.pageSize = 10
      this.multipleSelection = []
      this.$refs.multipleTable.clearSelection()
      this.getDataList(this.ruleForm, this.pageOptions)
    },
    // 切换页码
    handleCurrentChange(val) {
      this.pageOptions.pageIndex = val
      this.getDataList(this.ruleForm, this.pageOptions)
    },
    // 切换每页多少条数据，每页显示多少条改变时触发
    handleSizeChange(val) {
      this.pageOptions.pageSize = val
      this.getDataList(this.ruleForm, this.pageOptions)
    },
    // 设置发券方式回调
    handleClear () {
      this.multipleSelection = []
      this.$refs.multipleTable.clearSelection();
      this.ruleSelf.userNum = ''
    },
    // 立即召唤
    async callBackNow() {
       try {
          const res = await isCreateActive({ gasId: this.ruleForm.gasId, activeType: 1 })
          const { canCreate, message } = res.result
          if(res.code !== 200) return
          if (!canCreate) {
            this.$message.warning(message)
            return
          }
        } catch(e) {
          console.log(e)
        }
      if (this.sendType === '0' &&  this.allTotal === 0) {
        this.$message({ message: '当前油站没有符合发券的人', type: 'warning' })
        return
      }
      if (this.sendType === '2' && this.ruleSelf.userNum === '') {
        this.$message({ message: '请填写人数', type: 'warning' })
        return
      }
      if (this.sendType === '1' && this.multipleSelection.length === 0) {
        this.$message({ message: '请勾选人数', type: 'warning' })
        return
      }
      // 获取油站的全量信息
      const gasInfo = this.gasOptions.filter(item => {
        if (item.gasId === this.ruleForm.gasId) { return item }
      })
      // 组装参数
      const params = Object.assign({}, this.ruleForm)
      params.gasName = gasInfo[0].gasName
      params.gasId = gasInfo[0].gasId
      params.sendType = this.sendType // 0-全部 1-手动 2-自定义
      switch (params.sendType) {
        case '0':
          params.sendType = '0'
          if (this.allTotal > this.valid.max_user_size.max) {
            params.guessPeople = this.valid.max_user_size.max
          } else {
            params.guessPeople = this.allTotal
          }
          break
        case '1':
          {
            const copy = this.multipleSelection.map(item => { return item.userId})
            params.userIdsJson = JSON.stringify(copy)
            params.guessPeople = this.multipleSelection.length
            break
          }
        case '2':
          params.userNum = this.ruleSelf.userNum
          params.guessPeople = this.ruleSelf.userNum
          break
        default:
          break
      }
      this.passParams = params // 把参数全部带给召唤弹框
      this.dialogTableVisible = true
      this.resetInfo = true
    },
    // 获取周边司机接口列表方法
    async getDataList(ruleForm, pageOptions) { // 获取订单列表
      const paramsCopy = Object.assign({}, ruleForm, pageOptions)
      this.loading = true
      try {
        const { code, result, totalRow } = await aroundDriverList(paramsCopy)
        if (code !== 200) return
        this.tableData = result ? result : []
        this.allTotal = totalRow
      } catch (error) {
        console.log(error.message)
      } finally {
        this.loading = false
      }
    },
    // 校验接口
    async checkDoorApi () {
      try {
        const { code, result } = await checkDoor()
        if (code !== 200) return
        this.valid = result
      } catch (err) {
        console.log(err)
      }
    },
    // 获取油站
    async getAllGasStations (gasId) {
      try {
        const { code, result = [] } = await getAllGasInfoList()
        if(code !== 200) return
        this.gasOptions = result
        const defaultGasId = gasId || result[0].gasId
        this.ruleForm.gasId = defaultGasId
        this.queryInterest(defaultGasId)
        const res = await aroundOilNum({ gasId: defaultGasId })
        if(res.code !== 200) return
        this.oilOptions = res.result
        this.ruleForm.lastOrderOilNo = res.result[0].id
        this.activeSelectApi()
      } catch(e) {
        console.log(e)
      }
    },
    async queryInterest (gasId) {
      try {
        const { code, result = 0 } = await queryInterest({ gasId, interestCode: 'callRoundDriver' })
        if (code !== 200) return
        this.interest = result
      } catch (e) {
        console.log(e)
      }
    },
    // 下拉框接口
    async activeSelectApi() {
      try {
        const res = await activeSelect()
        if (res.code !== 200) return
        this.aroundOptions = res.result[0].selectList
        this.ruleForm.distance = res.result[0].selectList[0].key
        this.timeOptions = res.result[1].selectList
        this.ruleForm.laterTime = res.result[1].selectList[0].key
        this.searchList() // 表格数据
      } catch (error) {
        console.log(error.message)
      }
    }
  },
  mounted() {
    const { gasId } = this.$route.query
    this.getAllGasStations(gasId)
    this.checkDoorApi()
  }
}
</script>

<style lang="less" scoped>
.container {
  width: 100%;
}

.tips {
  font-size: 12px;
  font-weight: 400;
  color: red;
}

/deep/ .el-card__header {
  padding: 20px 10px;
  border-bottom: 1px solid #EBEEF5;
  box-sizing: border-box;
  font-size: 18px;
  font-weight: blod;
  color: #333333;
}

.box-card {
  width: 100%;
  box-shadow: none;
  border-radius: 0px;
  border: none;
}

.first {
  margin-top: 10px;
}

.btn {
  display: flex;
  justify-content: flex-end;
}

.accord {
  width: 100%;
  height: 48px;
  color: #4B7EFE;
  background: #EDF2FF;
  display: flex;
  justify-content: flex-start;
  align-items: center;
  padding-left: 20px;

  >span:nth-child(2) {
    font-size: 18px;
    font-weight: 500;
  }
}

.people-warp {
  height: 40px;
  display: flex;
  justify-content: flex-start;
  align-items: center;
}

.people {
  display: flex;
  justify-content: flex-start;
  align-items: center;
  margin-top:20px;
  .el-input {
    width: 100px;
    margin-right: 10px;
  }

  >span {
    color: #606266;
  }
}

.call {
  margin-top: 10px;

  .el-button {
    width: 200px;
  }
}

.table {
  margin-top: 10px;
}

.block {
  margin: 20px 10px;
  text-align: right;
}
</style>
